package com.ibpd.shopping.web.controller.shopInterface;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonBeanProcessor;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.helper.StringUtil;
import org.restlet.engine.util.DateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ibpd.dao.impl.ServiceProxyFactory;
import com.ibpd.henuocms.common.StringJsonArrayProgressor;
import com.ibpd.henuocms.exception.IbpdException;
import com.ibpd.henuocms.web.controller.manage.BaseController;
import com.ibpd.shopping.assist.ExtCartEntity;
import com.ibpd.shopping.assist.ExtCartInfo;
import com.ibpd.shopping.assist.ExtEvaluationEntity;
import com.ibpd.shopping.assist.ExtMallHomePageEntity;
import com.ibpd.shopping.assist.ExtOrderEntity;
import com.ibpd.shopping.assist.ExtOrderInfoEntity;
import com.ibpd.shopping.assist.ExtProductEntity;
import com.ibpd.shopping.assist.ExtTenantCartEntity;
import com.ibpd.shopping.assist.ExtTenantEntity;
import com.ibpd.shopping.entity.AccountEntity;
import com.ibpd.shopping.entity.AddressEntity;
import com.ibpd.shopping.entity.CartEntity;
import com.ibpd.shopping.entity.CatalogEntity;
import com.ibpd.shopping.entity.EvaluationEntity;
import com.ibpd.shopping.entity.ExpressEntity;
import com.ibpd.shopping.entity.FavoriteEntity;
import com.ibpd.shopping.entity.MallHomePageEntity;
import com.ibpd.shopping.entity.OrderEntity;
import com.ibpd.shopping.entity.OrderShipEntity;
import com.ibpd.shopping.entity.OrderTmpEntity;
import com.ibpd.shopping.entity.OrderdetailEntity;
import com.ibpd.shopping.entity.OrderpayEntity;
import com.ibpd.shopping.entity.ProductEntity;
import com.ibpd.shopping.entity.SpecEntity;
import com.ibpd.shopping.entity.TenantEntity;
import com.ibpd.shopping.service.MallHomePage.IMallHomePageService;
import com.ibpd.shopping.service.MallHomePage.MallHomePageServiceImpl;
import com.ibpd.shopping.service.account.AccountServiceImpl;
import com.ibpd.shopping.service.account.IAccountService;
import com.ibpd.shopping.service.address.AddressServiceImpl;
import com.ibpd.shopping.service.address.IAddressService;
import com.ibpd.shopping.service.area.AreaServiceImpl;
import com.ibpd.shopping.service.area.IAreaService;
import com.ibpd.shopping.service.cart.CartServiceImpl;
import com.ibpd.shopping.service.cart.ICartService;
import com.ibpd.shopping.service.catalog.CatalogServiceImpl;
import com.ibpd.shopping.service.catalog.ICatalogService;
import com.ibpd.shopping.service.evaluation.EvaluationServiceImpl;
import com.ibpd.shopping.service.evaluation.IEvaluationService;
import com.ibpd.shopping.service.express.ExpressServiceImpl;
import com.ibpd.shopping.service.express.IExpressService;
import com.ibpd.shopping.service.favorite.FavoriteServiceImpl;
import com.ibpd.shopping.service.favorite.IFavoriteService;
import com.ibpd.shopping.service.order.IOrderService;
import com.ibpd.shopping.service.order.OrderServiceImpl;
import com.ibpd.shopping.service.orderDetail.IOrderdetailService;
import com.ibpd.shopping.service.orderDetail.OrderdetailServiceImpl;
import com.ibpd.shopping.service.orderShip.IOrderShipService;
import com.ibpd.shopping.service.orderShip.OrderShipServiceImpl;
import com.ibpd.shopping.service.orderpay.IOrderpayService;
import com.ibpd.shopping.service.orderpay.OrderpayServiceImpl;
import com.ibpd.shopping.service.ordertmp.IOrderTmpService;
import com.ibpd.shopping.service.ordertmp.OrderTmpServiceImpl;
import com.ibpd.shopping.service.product.IProductService;
import com.ibpd.shopping.service.product.ProductServiceImpl;
import com.ibpd.shopping.service.spec.ISpecService;
import com.ibpd.shopping.service.spec.SpecServiceImpl;
import com.ibpd.shopping.service.tenant.ITenantService;
import com.ibpd.shopping.service.tenant.TenantServiceImpl;
@Controller()
public class Inter_Product  extends BaseController{
	Logger logger=Logger.getLogger(Inter_Product.class);
	public static final Object insert_favorite_lock = new Object();//收藏夹锁.防止添加重复记录
	public static final Object product_stock_lock=new Object();
	public static final String orderpay_paymethod_alipayescow = "alipayescow";//支付宝纯担保交易接口
	@RequestMapping("addToFavorite.do")
	public void addToFavorite(HttpServletResponse resp,HttpServletRequest req,String type,String tenantId,String  productId) throws IOException{
		if(StringUtils.isBlank(type)){
			super.printMsg(resp, "-2", "-1", "参数不正确");
			return;
		}
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		IAccountService accServ=(IAccountService) getService(AccountServiceImpl.class);
		AccountEntity acc=accServ.getEntityById(super.getCurrentLoginedUserId(req));
		
//		AccountEntity acc = InterfaceUtil.getLoginedAccountInfo(req.getSession());
		if(acc==null || StringUtils.isBlank(acc.getAccount())){
			super.printMsg(resp, "-3", "-1", "尚未登录或登录已经失效");
			return;
		}
		Integer tp=0;
		if(type.trim().toLowerCase().equals("product")){
			tp=FavoriteEntity.TYPE_PRODUCT;
		}else{
			tp=FavoriteEntity.TYPE_TENANT;
		}
		FavoriteEntity favorite = new FavoriteEntity();
		favorite.setType(tp);
		favorite.setAccount(acc.getAccount());
		favorite.setAccId(acc.getId());
		favorite.setProductId(Long.parseLong((productId==null?"-1":productId)));
		favorite.setTenantId(Long.parseLong(tenantId==null?"-1":tenantId));
		favorite.setCreatetime(new Date());
		Integer result = null;
		IFavoriteService favoriteService=(IFavoriteService) getService(FavoriteServiceImpl.class);
		synchronized (insert_favorite_lock) {
			if(favoriteService.selectCount(favorite) == 0){
				favoriteService.saveEntity(favorite);
				result =0;//添加成功
			}else{
				result =1;//已经添加过了
			}
		}
//		favoriteService.getDao().clearCache();
		if(result==0){
			super.printMsg(resp, "0", "0", "添加成功");
		}else{
			super.printMsg(resp, "-1", "-1", "已经添加过了");
		}
	}
	@RequestMapping("getFavoriteList.do")
	public void getFavoriteList(HttpServletResponse resp,HttpServletRequest req,String type) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		if(StringUtils.isBlank(type)){
			super.printMsg(resp, "-2", "-1", "参数不正确");
			return;
		} 
		IAccountService accServ=(IAccountService) getService(AccountServiceImpl.class);
//		accServ.getDao().clearCache();
		AccountEntity acc=accServ.getEntityById(super.getCurrentLoginedUserId(req));
		
//		AccountEntity acc = InterfaceUtil.getLoginedAccountInfo(req.getSession());
		if(acc==null || StringUtils.isBlank(acc.getAccount())){
			super.printMsg(resp, "-2", "-1", "尚未登录或登录已经失效");
			return;
		}
		Integer tp=0;
		if(type.trim().toLowerCase().equals("product")){
			tp=FavoriteEntity.TYPE_PRODUCT;
		}else{
			tp=FavoriteEntity.TYPE_TENANT;
		}
		IFavoriteService favServ=(IFavoriteService) getService(FavoriteServiceImpl.class);
		List<FavoriteEntity> favList=favServ.getFavoriteListByAccount(acc.getId());
		if(favList!=null && favList.size()>0){
			String ids="";
			for(FavoriteEntity f:favList){
				if(tp.equals(f.getType())){
					if(f.getType().equals(FavoriteEntity.TYPE_PRODUCT))
						ids+=f.getProductId()+",";
					else
						ids+=f.getTenantId()+",";
				}
			}
			if(ids.length()>0) 
				ids=ids.substring(0,ids.length()-1);
			else //
				ids="-1";
			String[] idss=ids.split(",");
			if(tp==FavoriteEntity.TYPE_PRODUCT){
				IProductService productServ=(IProductService)getService(ProductServiceImpl.class);
				List<ProductEntity> prodList =productServ.getListByIds(idss);
				List<ExtProductEntity> extList=new ArrayList<ExtProductEntity>();
				if(prodList!=null){
					ITenantService ts=(ITenantService) getService(TenantServiceImpl.class);
					for(ProductEntity pe:prodList){
						pe.setProductHTML("");
						ExtProductEntity e=new ExtProductEntity(pe,null,null);
						TenantEntity t=ts.getEntityById(e.getTenantId());
						if(t!=null){
							e.setTenantLogo(t.getLogo());
							e.setTenantName(t.getTenantName());
						}
						extList.add(e);
					}
				}
				super.sendJsonByList(resp, extList, Long.valueOf(favList.size()));				
			}else{
				ITenantService ts=(ITenantService) getService(TenantServiceImpl.class);
				List<TenantEntity> tList=ts.getListByIds(idss);
				if(tList==null){
					super.printMsg(resp, "-3", "-1", "没有收藏");
					return;
				}
				List<ExtTenantEntity> extList=new ArrayList<ExtTenantEntity>();
				for(TenantEntity t:tList){ //asdfasdfasfafsdfsdfs
					ExtTenantEntity e=new ExtTenantEntity(t);
					IProductService ps2=(IProductService) getService(ProductServiceImpl.class);
					List<ProductEntity> pl=ps2.getListByTenantId(e.getId(),5);
					e.setProductList(pl);
					extList.add(e);
				}
//				List<Hashtable<String,String>> lst=convertToHashTable(extList);
				try {
					JsonConfig jsonConfig = new JsonConfig();  
					jsonConfig.registerJsonBeanProcessor(ProductEntity.class, ProductJsonBeanProgressor());
					jsonConfig.registerJsonValueProcessor(Long.class, new StringJsonArrayProgressor()); 
					jsonConfig.registerJsonValueProcessor(Integer.class, new StringJsonArrayProgressor()); 
					jsonConfig.registerJsonValueProcessor(Date.class, new StringJsonArrayProgressor()); 
				    JSONArray jsonArray = JSONArray.fromObject( extList,jsonConfig );
//					List<Hashtable<String, String>> tmpMap=super.convertToHashTable(extList);
					
//				    JSONArray jsonArray = JSONArray.fromObject( tmpMap );
				    
					PrintWriter out = resp.getWriter();
					String json=jsonArray.toString().replace("\"[", "[").replace("]\"", "]");//.replace("\"", "");
					 out.print("{\"total\":"+extList.size()+",\"rows\":"+json+"}");
					 out.flush();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}else{
			super.sendJsonByList(resp, new ArrayList<ProductEntity>(), 0L);
		}
	}
	private JsonBeanProcessor ProductJsonBeanProgressor() {
		// TODO Auto-generated method stub
		return null;
	}
	@RequestMapping("removeFavorite.do")
	public void removeFavorite(HttpServletResponse resp,HttpServletRequest req,String type,String ids) throws IOException{
//		if(StringUtils.isBlank(productIds) && StringUtils.isBlank(tenantIds)){
//			super.printMsg(resp, "-2", "-1", "参数不正确");
//			return;
//		}
		ids=ids==null?"":ids;
		type=type==null?"":type;
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
//		IAccountService accServ=(IAccountService) getService(AccountServiceImpl.class);
//		AccountEntity acc=accServ.getEntityById(super.getCurrentLoginedUserId(req));
		
//		AccountEntity acc = InterfaceUtil.getLoginedAccountInfo(req.getSession());
//		if(acc==null || StringUtils.isBlank(acc.getAccount())){
//			super.printMsg(resp, "-2", "-1", "尚未登录或登录已经失效");
//			return;
//		}
		IFavoriteService favoriteService=(IFavoriteService) getService(FavoriteServiceImpl.class);
		String[] idStrs=ids.split(","); 
		List<FavoriteEntity> favList=favoriteService.getFavoriteListByAccount(super.getCurrentLoginedUserId(req));
		String rtnMsg="";
		if(type.trim().toLowerCase().equals("product")){
			for(String id:idStrs){
				if(StringUtil.isNumeric(id)){
					Boolean s=false;
					for(FavoriteEntity f:favList){
						if(f.getProductId().toString().equals(id)){
							s=true;
						}
					}
					if(s==false){
						rtnMsg+="不存在商品ID为"+id+"的收藏,";
					}else{
						favoriteService.removeFavoriteByProductId(super.getCurrentLoginedUserId(req),Long.valueOf(id));	
					}
				}
			}
			if(StringUtils.isBlank(rtnMsg)){
				super.printMsg(resp, "99", "99", "移除成功");
				return;
			}else{
				super.printMsg(resp, "99", "-1", rtnMsg);
				return;
			}
		}else if(type.trim().toLowerCase().equals("tenant")){
			for(String id:idStrs){
				if(StringUtil.isNumeric(id)){
					Boolean s=false;
					for(FavoriteEntity f:favList){
						if(f.getTenantId().toString().equals(id)){
							s=true;
						}
					}
					if(s==false){
						rtnMsg+="不存在商户ID为"+id+"的收藏,";
					}else{
						favoriteService.removeFavoriteByTenantId(super.getCurrentLoginedUserId(req),Long.valueOf(id));
					}
				}
			}
			if(StringUtils.isBlank(rtnMsg)){
				super.printMsg(resp, "99", "99", "移除成功");
				return;
			}else{
				super.printMsg(resp, "99", "-1", rtnMsg);
				return;
			}
		}else{
			super.printMsg(resp, "-2", "-1","参数错误!");
			return;
		}
	}
	@RequestMapping("getEvaluationList.do")
	public void getEvaluationList(HttpServletResponse resp,HttpServletRequest req,Long productId,Integer pageSize,Integer pageIndex) throws IOException{
		if(productId==null || productId<=0){
			super.printMsg(resp, "-2", "-1", "参数不正确");
			return;
		}
		Long userId=super.getCurrentLoginedUserId(req);
//		if(super.getCurrentLoginedUserId(req)==-1L){
//			super.printMsg(resp, "-1", "-1","请先登录!");
//			return;			
//		}
		pageSize=(pageSize==null)?10:pageSize;
		pageSize=(pageSize==-1 || pageSize==0)?10:pageSize; 
		pageIndex=(pageIndex==null)?0:pageIndex;
		pageIndex=(pageIndex<0)?0:pageIndex;
		IEvaluationService evalServ=(IEvaluationService) getService(EvaluationServiceImpl.class);
		if(userId==-1L){
			List<EvaluationEntity> evaList=evalServ.getList("from "+evalServ.getTableName()+" where productId="+productId,null,"createDate desc",pageSize,pageIndex);
			Long rowCount=evalServ.getRowCount(" where productId="+productId, null);
			IAccountService accServ=(IAccountService) getService(AccountServiceImpl.class);
			List<ExtEvaluationEntity> extList=new ArrayList<ExtEvaluationEntity>();
			for(EvaluationEntity e:evaList){
				ExtEvaluationEntity ext=new ExtEvaluationEntity(e);
				AccountEntity ae=accServ.getEntityById(e.getAccId());
				if(ae!=null){
					ext.setAccLogo(ae.getLogo());
					ext.setAccName(StringUtils.isBlank(ae.getNickname())?ext.getAccName():ae.getNickname());
//					extList.add(ext);
				}
				extList.add(ext);
			}
			super.sendJsonByList(resp, extList, rowCount);
		}else{
			List<EvaluationEntity> evaList=evalServ.getListByAccountId(super.getCurrentLoginedUserId(req),productId,pageSize,pageIndex);
			if(evaList==null){
				super.sendJsonByList(resp, new ArrayList<EvaluationEntity>(), 0L);
			}else{
				Long rowCount=evalServ.getRowCount(" where accId="+super.getCurrentLoginedUserId(req)+" and productId="+productId, null);
				IAccountService accServ=(IAccountService) getService(AccountServiceImpl.class);
				List<ExtEvaluationEntity> extList=new ArrayList<ExtEvaluationEntity>();
				for(EvaluationEntity e:evaList){
					ExtEvaluationEntity ext=new ExtEvaluationEntity(e);
					AccountEntity ae=accServ.getEntityById(super.getCurrentLoginedUserId(req));
					if(ae!=null){
						ext.setAccLogo(ae.getLogo());
						extList.add(ext);
					}else{
						extList.add(ext);
					}
				}
				super.sendJsonByList(resp, extList, rowCount);
			}
		}
	}
	@RequestMapping("checkProductEvaluation.do")
	public void checkProductEvaluation(HttpServletResponse resp,HttpServletRequest req,Long productId,Long orderId) throws IOException{
		if(productId==null || productId<=0){
			super.printMsg(resp, "-1", "-1", "参数不正确");
			return;
		}
		if(orderId==null || orderId<=0){
			super.printMsg(resp, "-1", "-1", "参数不正确");
			return;
		}
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-2", "-1","请先登录!");
			return;			
		}
		if(checkProductEvaluation(Long.valueOf(super.getCurrentLoginedUserId(req)),productId,orderId)){
			super.printMsg(resp, "-3", "-1","已经评价过了");
			return;		 
		}else{
			super.printMsg(resp, "1", "0","尚未评价");
			return;
		}
	}
	private Boolean checkProductEvaluation(Long userId,Long productId,Long orderId){
		IOrderdetailService detaServ=(IOrderdetailService) getService(OrderdetailServiceImpl.class);
		List<OrderdetailEntity> detaList=detaServ.getListByOrderId(orderId);
		if(detaList==null)
			return false;
		OrderdetailEntity currDeta=null;
		for(OrderdetailEntity d:detaList){
			if(d.getProductID().equals(productId)){
				currDeta=d;
				break;
			}
		}
		if(currDeta==null){
			return false;
		}else{
			if(currDeta.getIsComment().toLowerCase().trim().equals("y")){
				return true;
			}else{
				return false;
			}
		}
//		IEvaluationService evalServ=(IEvaluationService) getService(EvaluationServiceImpl.class);
//		List l=evalServ.getList("from "+evalServ.getTableName()+" where accId="+userId+" and productId="+productId+" and orderId="+orderId,null);
//		if(l.size()>0)
//			return true;
//		else
//			 return false;
	}
	@RequestMapping("submitEvaluation.do")
	public void submitEvaluation(HttpServletResponse resp,HttpServletRequest req,Long productId,Long orderId,Integer leval,String content) throws IOException{
		if(productId==null || productId<=0){
			super.printMsg(resp, "-2", "-1", "参数不正确");
			return;
		}
		if(orderId==null || orderId<=0){
			super.printMsg(resp, "-2", "-1", "参数不正确");
			return;
		}
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		if(checkProductEvaluation(Long.valueOf(super.getCurrentLoginedUserId(req)),productId,orderId)){
			super.printMsg(resp, "-4", "-1","已经评价过了");
			return;		
		} 
		leval=(leval==null)?5:leval;
		content=(content==null)?"":content;
		IAccountService as=(IAccountService) getService(AccountServiceImpl.class);
		AccountEntity ae=as.getEntityById(super.getCurrentLoginedUserId(req));
		if(ae==null){
			super.printMsg(resp, "-3", "-1", "参数错误");
			return;
		}
		IOrderdetailService detaServ=(IOrderdetailService) getService(OrderdetailServiceImpl.class);
		List<OrderdetailEntity> detaList=detaServ.getListByOrderId(orderId);
		if(detaList==null){
			super.printMsg(resp, "-5", "-1", "没有该订单");
			return;
		}
		OrderdetailEntity currDetail=null;
		for(OrderdetailEntity d:detaList){
			if(d.getProductID().equals(productId)){
				currDetail=d;
				continue;
			}
		}
		if(currDetail==null){
			super.printMsg(resp, "-6", "-1", "订单中没有该商品");
			return;
		}
		IEvaluationService evalServ=(IEvaluationService) getService(EvaluationServiceImpl.class);
		EvaluationEntity e=new EvaluationEntity();
		e.setAccId(ae.getId());
		e.setAccName(ae.getAccount());
		e.setContent(content);
		e.setCreateDate(new Date());
		e.setLevel(leval); 
		e.setProductId(productId);
		e.setOrderId(orderId);
		evalServ.saveEntity(e);
		currDetail.setIsComment("y");
		detaServ.saveEntity(currDetail);
		super.printMsg(resp, "1", "1", "保存成功");
	}
	@RequestMapping("getCatalogList.do")
	public void getCatalogList(HttpServletResponse resp,HttpServletRequest req,Long pId) throws IOException{
		if(pId==null || pId<0L)
			pId=0L;
		ICatalogService cs=(ICatalogService) getService(CatalogServiceImpl.class);
		List<CatalogEntity> cl=cs.getList(pId);
		super.sendJsonByList(resp, cl, Long.valueOf(cl.size()));
	}
	@RequestMapping("checkProductIsFavorite.do")
	public void checkProductIsFavorite(HttpServletResponse resp,HttpServletRequest req,Long userId,Long productId) throws IOException{
		if(userId==null || productId==null){
			super.printMsg(resp, "-1", "-1", "参数不足");
			return;
		}
		if(userId<=0 || productId<=0){
			super.printMsg(resp, "-1", "-1", "参数不足");
			return;
		}
		IAccountService as=(IAccountService) getService(AccountServiceImpl.class);
		AccountEntity ae=as.getEntityById(userId);
		if(ae==null){
			super.printMsg(resp, "-2", "-1", "参数错误");
			return;
		}
		IFavoriteService favServ=(IFavoriteService) getService(FavoriteServiceImpl.class);
		List<FavoriteEntity> favList=favServ.getFavoriteListByAccount(ae.getId());
		Boolean rtn=false;
		if(favList!=null){
			for(FavoriteEntity fav:favList){
				if(fav.getProductId().equals(productId)){
					rtn=true;
					break;
				}
			}
		}
		super.printMsg(resp, "1", rtn.toString(), (rtn)?"已收藏":"未收藏");
	}
	@RequestMapping("checkTenantIsFavorite.do")
	public void checkTenantIsFavorite(HttpServletResponse resp,HttpServletRequest req,Long userId,Long tenantId) throws IOException{
		if(userId==null || tenantId==null){
			super.printMsg(resp, "-1", "-1", "参数不足");
			return;
		}
		if(userId<=0 || tenantId<=0){
			super.printMsg(resp, "-1", "-1", "参数不足");
			return;
		}
		IAccountService as=(IAccountService) getService(AccountServiceImpl.class);
		AccountEntity ae=as.getEntityById(userId);
		if(ae==null){
			super.printMsg(resp, "-2", "-1", "参数错误");
			return;
		}
		IFavoriteService favServ=(IFavoriteService) getService(FavoriteServiceImpl.class);
		List<FavoriteEntity> favList=favServ.getFavoriteListByAccount(ae.getId());
		Boolean rtn=false;
		if(favList!=null){
			for(FavoriteEntity fav:favList){
				if(fav.getTenantId().equals(tenantId)){
					rtn=true;
					break;
				}
			}
		}
		super.printMsg(resp, "1", rtn.toString(), (rtn)?"已收藏":"未收藏");
	}
	@RequestMapping("getProductList.do")
	public void getProductList(HttpServletResponse resp,HttpServletRequest req,Long catalogId,Integer pageSize,Integer pageIndex,String queryString,String orderField,String  orderType) throws IOException{
		if(catalogId==null || catalogId<0L){
			super.printMsg(resp, "-2", "-1", "参数不正确");
			return;
		}
		String _orderType=null;
		orderType=(orderType==null)?"asc":orderType;
		orderField=(orderField==null)?"id":orderField;
		if(!StringUtils.isBlank(orderField)){
			_orderType=orderField+" "+((StringUtils.isBlank(orderType))?"asc":orderType);
		}
		pageSize=(pageSize==null)?10:pageSize;
		pageSize=(pageSize==-1 || pageSize==0)?10:pageSize;
		pageIndex=(pageIndex==null)?1:pageIndex;
		pageIndex=(pageIndex<0)?0:pageIndex;
		//pageIndex=pageSize*pageIndex;
		IProductService productServ=(IProductService)getService(ProductServiceImpl.class);
		List<ExtProductEntity> prodList =productServ.getExtListByCatalogId(catalogId,pageSize,pageIndex,queryString,_orderType);
		Long rowCount=productServ.getRowCount(catalogId,queryString);
		ITenantService ts=(ITenantService) getService(TenantServiceImpl.class);
		if(prodList!=null){
			for(ExtProductEntity prod:prodList){
				prod.setProductHTML("");
				if(prod.getTenantId()<=0L){
					prod.setTenantName("自营");
					prod.setTenantLogo("defaultLogo.png");
				}else{
					TenantEntity t=ts.getEntityById(prod.getTenantId());
					if(t==null){
						prod.setTenantName("");
						prod.setTenantLogo("defaultLogo.png");
					}else{
						prod.setTenantName(t.getTenantName());
						prod.setTenantLogo(t.getLogo());
					}
				}
			}
		}
		super.sendJsonByList(resp, prodList, rowCount);
	}
	@RequestMapping("getProductListByTenantId.do")
	public void getProductListByTenantId(HttpServletResponse resp,HttpServletRequest req,Integer pageSize,Long tenantId,Integer pageIndex,String orderField,String  orderType) throws IOException{
		String _orderType=null;
		orderType=(orderType==null)?"asc":orderType;
		orderField=(orderField==null)?"order":orderField;
		if(!StringUtils.isBlank(orderField)){
			_orderType=orderField+" "+((StringUtils.isBlank(orderType))?"asc":orderType);
		}
		pageSize=(pageSize==null)?10:pageSize;
		pageSize=(pageSize==-1 || pageSize==0)?10:pageSize;
		pageIndex=(pageIndex==null)?1:pageIndex;
		pageIndex=(pageIndex<0)?0:pageIndex;  
		//pageIndex=pageSize*pageIndex;
		IProductService productServ=(IProductService)getService(ProductServiceImpl.class);
		List<ProductEntity> prodList =productServ.getList("from "+productServ.getTableName()+" where tenantId="+tenantId+" and status="+ProductEntity.Status_Pass, null, _orderType, pageSize, pageIndex);
		Long rowCount=productServ.getRowCount("where tenantId="+tenantId+" and status="+ProductEntity.Status_Pass, null);
		if(prodList!=null){
			for(ProductEntity prod:prodList){
				prod.setProductHTML("");
			}
		}
		super.sendJsonByList(resp, prodList, rowCount);
	}
	@RequestMapping("getProductInfo.do")
	public void getProductInfo(HttpServletResponse resp,HttpServletRequest req,Long productId) throws IOException{
//		if(super.getCurrentLoginedUserId(req)==-1L){
//			super.printMsg(resp, "-1", "-1","请先登录!");
//			return;			
//		}
		if(productId==null || productId<=0L){
			super.printMsg(resp, "-2", "-1", "参数不正确");
			return;
		}
		IProductService productServ=(IProductService)getService(ProductServiceImpl.class);
		ExtProductEntity p=productServ.getProductInfo(productId);
		if(p==null){
			super.printMsg(resp, "-1", "-1", "没有该商品信息");
			return;			
		}
//		if(p.getStock()<=0){
//			super.printMsg(resp, "-3", "-1", "商品库存为0");
//			return;	
//		}
		if(!p.getStatus().equals(ProductEntity.Status_Pass)){
			super.printMsg(resp, "-4", "-1", "商品已下架");//这个判断一般用不到
			return;	
		}
		p.setProductHTML("");
		ITenantService ts=(ITenantService) getService(TenantServiceImpl.class);
		TenantEntity t=ts.getEntityById(p.getTenantId());
		p.setTenantName(t==null?"":t.getEntFullName());
		p.setTenantLogo(t==null?"":t.getLogo());
		p.setUserId(super.getCurrentLoginedUserId(req));
		IFavoriteService favServ=(IFavoriteService) getService(FavoriteServiceImpl.class);
		List<FavoriteEntity> favList=favServ.getFavoriteListByAccount(p.getUserId());
		Boolean rtn=false;
		if(favList!=null){
			for(FavoriteEntity fav:favList){
				if(fav.getProductId().equals(productId)){
					rtn=true;
					break;
				}
			}
		}
		p.setIsFavorite(rtn);
		List<ExtProductEntity> ep=new ArrayList<ExtProductEntity>();
		ep.add(p);
		super.sendJsonByList(resp, ep, 1L);
	}
	/**
	 * 获取商品同一分类下的相关商品，检索方式为根据searchKey检索（可不关注此项）<br/>该接口最多返回20条相关信息，并且不返回本身请求的内容<br />
	 * 具体实现：用现有商品的seachkey作为关键字，在商品的title字段中做模糊查询
	 * @param resp
	 * @param req
	 * @param productId //商品ID
	 * @throws IOException
	 */
	@RequestMapping("getAboutProductList.do")
	public void getAboutProductList(HttpServletResponse resp,HttpServletRequest req,Long productId) throws IOException{
		//原系统中是没有这些逻辑的，我这里计划使用 同类目下、同关键字的商品来显示，两者的关系是or
		if(productId==null || productId<=0L){
			super.printMsg(resp, "-1", "-1", "参数不正确");
			return;	
		}
		IProductService ps=(IProductService) getService(ProductServiceImpl.class);
		List<ProductEntity> pl=ps.getAboutProductList(productId);
		if(pl==null){
			super.printMsg(resp, "-2", "-1", "没有相关商品");
			return;	
		}
		for(ProductEntity p:pl){
			p.setProductHTML("");
		}
		super.sendJsonByList(resp, pl, Long.valueOf(pl.size()));
	}
	@RequestMapping("getProductContent.do")
	public void getProductContent(HttpServletResponse resp,HttpServletRequest req,Long productId) throws IOException{
		if(productId==null || productId<=0L){
			super.printMsg(resp, "-1", "-1", "参数不正确");
			return;	
		}
		IProductService ps=(IProductService) getService(ProductServiceImpl.class);
		ProductEntity pe=ps.getEntityById(productId);
		if(pe==null){
			super.printMsg(resp, "-2", "-1", "没有该商品");
			return;				
		}
		resp.getWriter().write(pe.getProductHTML());
	}
	private ExtCartInfo fillCartInfo(List<CartEntity> lst,Long userId){
		ExtCartInfo rtn=new ExtCartInfo();
		if(lst==null || lst.size()==0)
			return rtn;
		else{
			rtn.setProductList(lst);
			rtn.setAmount(getPriceAmount(lst).toString());
			rtn.setTotalExchangeScore(getScoreTotal(lst));
			return rtn;
		}
	}
	private Float getPriceAmount(List<CartEntity> lst){
		if(lst==null || lst.size()==0)
			return 0f;
		Float total=0f;
		for(CartEntity c:lst){
			total=total+(c.getSpecPrice()*c.getBuyCount());
		}
		return total;
	}
	private Integer getScoreTotal(List<CartEntity> lst){
		if(lst==null || lst.size()==0)
			return 0;
		Integer total=0;
		for(CartEntity c:lst){
			total=total+((c.getScore()==null)?0:c.getScore());
		}
		return total;
	}
	private Integer getProductScore(Long productId,Integer buyCount){
		IProductService ps=(IProductService) getService(ProductServiceImpl.class);
		ProductEntity p=ps.getEntityById(productId);
		if(p==null)
			return 0;
		return ((p.getScore()==null)?0:p.getScore())*buyCount;
	} 
	@RequestMapping("addToCart.do")
	public void addToCart(HttpServletResponse resp,HttpServletRequest req,Long productId,Integer buyCount,Long buySpecId) throws IOException{		
		logger.error("ProductAction.cart...");
		DecimalFormat df = new DecimalFormat("0.00");
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		if(StringUtils.isBlank(productId.toString()) || buyCount<=0){
			super.printMsg(resp, "-1", "-1","参数错误!");
			return;
		}
		
		/**
		 * 检查商品是否已经下架，如果已下架，则提醒用户
		 */
		IProductService prodServ=(IProductService) getService(ProductServiceImpl.class);
		ProductEntity product=prodServ.getEntityById(productId);
		if(product==null){
			super.printMsg(resp, "-1", "-1","参数错误!");
			return;
		}
		if(product.getStatus()==ProductEntity.Status_Pass){
			super.printMsg(resp, "-2", "-2", "很抱歉，商品已下架暂时无法购买!");
			return;
		}
		/**
		 * 检查库存是否已超卖，如果超库存不足，则提醒用户
		 */
		ISpecService peServ=(ISpecService) getService(SpecServiceImpl.class);
		buySpecId=(buySpecId==null)?-1L:buySpecId;
		if(buySpecId==-1L){
			if((product.getStock()-buyCount)<0){
				super.printMsg(resp, "-4", "-4", "很抱歉，该商品库存不足!");
				return;
			}
		}else if(buySpecId>=0){
			SpecEntity spec=peServ.getEntityById(buySpecId);
			if(spec==null){
				super.printMsg(resp, "-3", "-3", "很抱歉，没有该规格的商品!");
				return;
			}
			String stockString=spec.getSpecStock();
			Integer stock=0;
			if(StringUtil.isNumeric(stockString.trim())){
				stock=Integer.valueOf(stockString);			
			}
			if((stock-buyCount)<0){
				super.printMsg(resp, "-4", "-4", "很抱歉，该商品库存不足!");
				return;
			}
		}
		/**
		 * 商品状态正常、且库存正常，则可以加载客户的购物车了，将该商品跟购物车里的作比较，有则加个数，无则新加入
		 */
		ICartService cartServ=(ICartService) getService(CartServiceImpl.class);
		List<CartEntity> cartProductList=cartServ.getCartProductListByUserId(super.getCurrentLoginedUserId(req));
		ExtCartInfo cartInfo = fillCartInfo(cartProductList,super.getCurrentLoginedUserId(req));
		if(cartInfo==null){
			cartInfo = new ExtCartInfo();
		}		
		//检查指定的产品是否已购买到购物车，购买了则数量++，否则查询后添加到购物车
		boolean exists = false;
		CartEntity cartProduct=null;
		for(int i=0;i<cartInfo.getProductList().size();i++){
			CartEntity p = cartInfo.getProductList().get(i);
			if(buySpecId==null || buySpecId<=0){
				buySpecId=-1L;
				if(p.getSpecId()==null || p.getSpecId()<=0L){
					p.setSpecId(-1L);
				}
			}
			if(p.getProductId().equals(productId) && p.getSpecId().equals(buySpecId)){
				p.setBuyCount(p.getBuyCount()+buyCount);
				logger.error("商品已购买，只对数量进行++，总数="+p.getBuyCount());
				p.setScore(((p.getScore()==null)?0:p.getScore())+getProductScore(productId,buyCount));
				//p.setSpecPrice(product.getNowPrice());
				p.resetPrice();
				cartProduct=p;
				exists = true;
				super.printMsg(resp, "0", "0", "成功加入购物车");
			}
		}
		//如果购物车中不存在此商品，则添加到购物车
		if(!exists){
			cartProduct = new CartEntity(super.getCurrentLoginedUserId(req),productId,buySpecId,buyCount);
			
//			cartInfo.getProductList().add(cartProduct);
//			logger.error("添加商品到购物车!商品ID="+cartProduct.getId());	
//			cartInfo.totalCacl();//计算购物车中商品总金额
			super.printMsg(resp, "0", "0", "成功加入购物车");
		}
		ICartService cs=(ICartService) getService(CartServiceImpl.class);
		cs.saveEntity(cartProduct);
	}
	@RequestMapping("viewCart.do")
	public void viewCart(HttpServletResponse resp,HttpServletRequest req) throws IOException{
		ICartService cartServ=(ICartService) getService(CartServiceImpl.class);
		List<CartEntity> cartProductList=cartServ.getCartProductListByUserId(super.getCurrentLoginedUserId(req));
		Map<Long,List<CartEntity>> tenantProdMap=new HashMap<Long,List<CartEntity>>();
		if(cartProductList!=null){
			for(CartEntity cp:cartProductList){
				List<CartEntity> cList=tenantProdMap.get(cp.getTenantId());
				if(cList==null){
					cList=new ArrayList<CartEntity>();
				}
				cList.add(cp);
				tenantProdMap.put(cp.getTenantId(), cList);
			}
		}
		List<ExtTenantCartEntity> tenantList=new ArrayList<ExtTenantCartEntity>();	
		ITenantService tenantServ=(ITenantService) getService(TenantServiceImpl.class);
		for(Long id:tenantProdMap.keySet()){
			ExtTenantCartEntity ext=new ExtTenantCartEntity();
			ext.setProductList(tenantProdMap.get(id));
			ext.setTenantId(id);
			ext.setTenantName(getTenantName(tenantServ,id));
			ext.setAmount(getAmount(tenantProdMap.get(id)));
			tenantList.add(ext);
		}
		JsonConfig conf=getDefaultJsonConfig();
		JSONArray j=JSONArray.fromObject(tenantList,conf);
		super.printJsonData(resp, "{\"prodects\":"+j.toString()+"}");
	}
	private Float getAmount(List<CartEntity> cl){
		if(cl==null)
			return 0f;
		Float f=0f;
		for(CartEntity c:cl){
			f=f+c.getSpecPrice()*c.getBuyCount();
		}
		return f;
	}
	private String getTenantName(ITenantService ts,Long tId){
		if(tId==null)
			return "";
		if(tId==-1L){
			return "自营";
		}
		if(ts==null)
			return "";
		TenantEntity t=ts.getEntityById(tId);
		if(t==null)
			return "";
		return t.getTenantName();
	}
	@RequestMapping("submitCartOrder.do")
	public void submitCartOrder(HttpServletRequest req,HttpServletResponse resp,String params,Long addressId) throws IOException{
		//params's format:productId:specId:buyCount:expressId;
		//这里由于涉及到了多个商户的订单，让下单这块变得相对麻烦，先根据上面的格式分解要生成的订单数据，直到生成订单
		//最终返回的是一个订单号，但这里涉及到了多个订单，也就是多订单付款.
		//常规检测
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		
		IAccountService accServ=(IAccountService) getService(AccountServiceImpl.class);
		AccountEntity account=accServ.getEntityById(super.getCurrentLoginedUserId(req));
		if(account==null){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		
		DecimalFormat df = new DecimalFormat("0.00");
		if(params==null || addressId==null){
			super.printMsg(resp, "-2", "-2", "非法请求！");
			return;
		}
		if(StringUtils.isBlank(params) || addressId<=0){
			super.printMsg(resp, "-2", "-2", "非法请求！");
			return;
		}
		//先对参数进行分解
		String[] pms=params.split(";");
		IProductService prodServ=(IProductService) getService(ProductServiceImpl.class);
		ICartService cartServ=(ICartService) getService(CartServiceImpl.class);
		ISpecService specServ=(ISpecService) getService(SpecServiceImpl.class);
		IAddressService addServ=(IAddressService) getService(AddressServiceImpl.class);
		IExpressService expServ=(IExpressService) getService(ExpressServiceImpl.class);
		IOrderdetailService detaServ=(IOrderdetailService) getService(OrderdetailServiceImpl.class);
		List<ExtCartEntity> currentCartList=new ArrayList<ExtCartEntity>();
		List<CartEntity> allCartList=cartServ.getCartProductListByUserId(account.getId());
		//获取配送地址
		AddressEntity address = addServ.getEntityById(addressId);
		if(address==null){
			super.printMsg(resp,"-1","-1","根据ID="+addressId+"查询不到配送地址信息！");
			return;
		}
		for(String pm:pms){
			String[] ps=pm.split(":");
			if(ps.length==4){
				//根据需求，商品数量等以客户端的为主，那么这里也就不做参数内商品跟购物车内商品的对比了，直接处理就行
				String pId=ps[0];
				String specId=ps[1];
				String buyCount=ps[2];
				String expId=ps[3];
				//从购物车中检索，加入现在的list，并从购物车中移出该商品
				Long productId=Long.valueOf(pId);
				for(CartEntity cart:allCartList){
					if(cart.getProductId().equals(productId) && cart.getSpecId().equals(Long.valueOf(specId))){
						cart.setBuyCount(Integer.valueOf(buyCount));
						ExtCartEntity e=new ExtCartEntity(cart);
						e.setExpressId(Long.valueOf(expId));
						currentCartList.add(e);//这里将要下订单的商品统计出来
					}
				}
			}else{
				//数据格式错误，直接忽略
			}
		}
		//定义一个order的变量，用来记录最终到底有几个order生成，便于最终生成单号
		List<OrderEntity> allOrderList=new ArrayList<OrderEntity>();
		//要下订单的商品统计出来后,对这些信息进行下单
		Map<Long,List<ExtCartEntity>> tenantProdMap=new HashMap<Long,List<ExtCartEntity>>();
		if(currentCartList.size()>0){
			for(ExtCartEntity cart:currentCartList){
				///////////////////////////////////////////////
				ProductEntity pe=null;
				SpecEntity spec=null;
				String msg="";
				pe=prodServ.getEntityById(cart.getProductId());
				//判断商品状态是否正常
				if(pe==null){
					msg+="商品不存在;";
				}else if(!pe.getStatus().equals(ProductEntity.Status_Pass)){
					msg+="商品["+pe.getName()+"]已下架;";
				}else if(pe.getStock()==0){
					msg+="商品["+pe.getName()+"]已经卖完啦;";
				}
				if(!StringUtils.isBlank(msg)){
					super.printMsg(resp, "-4", "-1",msg);
					return;	
				}
				//根据商品以及规格判断是否有库存，如果有规格信息，则走规格的库存，否则走商品的库存
				Boolean stockIsSat=false;
				if(cart.getSpecId()==-1L){
					//走商品的库存
					if(pe==null){
						stockIsSat=false;
					}
					if(pe.getStock()>=cart.getBuyCount()){
						stockIsSat=true;
					}
				}else{
					//走规格的库存
					spec=specServ.getEntityById(cart.getSpecId());
					if(spec==null){
						stockIsSat=false;
					}
					if(Integer.valueOf(spec.getSpecStock())>=cart.getBuyCount()){
						stockIsSat=true;
					}
				}
				if(!stockIsSat){
					super.printMsg(resp, "-5", "-1","库存不足!");
					return;	
				}
				//获取配送方式
				ExpressEntity express = expServ.getEntityById(cart.getExpressId());
				if(express==null){
					super.printMsg(resp, "-7", "-7", "没有编码为"+cart.getExpressId()+"的配送方式！本次请求视为非法！");
					return;
				}
				cart.setExpress(express);
				cart.setAddress(address);
				List<ExtCartEntity> cList=tenantProdMap.get(cart.getTenantId());
				cList=(cList==null)?new ArrayList<ExtCartEntity>():cList;
				cList.add(cart);
				tenantProdMap.put(cart.getTenantId(), cList);
			}
			//根据tenantID归类后，根据这些信息 做订单，每个商户一个订单
			for(Long tenantId:tenantProdMap.keySet()){
////////////////////////////////////////////
				List<ExtCartEntity> cartInfo=tenantProdMap.get(tenantId);
				//创建订单对象
				OrderEntity order = new OrderEntity();
				order.setAccount(account.getAccount());
				order.setQuantity(cartInfo.size());
				order.setRebate(1d);
				order.setStatus(OrderEntity.order_status_init);
				order.setPaystatus(OrderEntity.order_paystatus_n);
				order.setOtherRequirement("");//附加要求
				
				//商品总金额
//				double ptotal = 0d;
				int score = 0;//订单积分 等于订单项中每个商品赠送的积分总和
				//创建订单明细集合
				List<OrderdetailEntity> orderdetailList = new LinkedList<OrderdetailEntity>();
				ExpressEntity curExpress=null;
				for (int i = 0; i < cartInfo.size(); i++) {
					ExtCartEntity product = cartInfo.get(i);
					curExpress=product.getExpress();
					OrderdetailEntity orderdetail = new OrderdetailEntity();
					orderdetail.setProductID(product.getProductId());//
					orderdetail.setGiftID("-1");//商品赠品ID
					orderdetail.setPrice(Double.valueOf(product.getSpecPrice().toString()));//商品现价
					orderdetail.setNumber(product.getBuyCount());//购买数
					order.setPtotal((order.getPtotal()==null?0d:order.getPtotal())+Double.valueOf(orderdetail.getPrice()*orderdetail.getNumber()));//订单商品总金额
//					order.setFee(order.getPtotal()>=product.getExpress().getExempt()?0f:product.getExpress().getFee());//订单配送费,包括满额免邮
//					order.setAmount(order.getPtotal()+order.getFee());//订单总金额 = 内存订单总金额 + 总配送费
					orderdetail.setProductName(product.getProductName());
					ProductEntity p=prodServ.getEntityById(product.getProductId());
					orderdetail.setTenantId(product.getTenantId());//如果没有对应的供应商，则 把该商品的订单定为总部商品
					orderdetail.setProductImage(p.getMaxPicture());
					orderdetail.setTotal(Double.valueOf(orderdetail.getPrice()) * orderdetail.getNumber());//订单项小计
					orderdetail.setScore(product.getScore());//活的赠送的积分
					if(product.getSpecId()!=null && product.getSpecId()>=0L){
						//按照规格计算
						orderdetail.setSpecInfo("尺寸:"+product.getSpecSize()+",颜色:"+product.getSpecColor());
//						ptotal+= Double.valueOf(product.getBuySpecInfo().getSpecPrice()) * product.getBuyCount();
//						score+= product.getScore();
					}else{
						orderdetail.setSpecInfo("无规格");
					}
//					ptotal+= Double.valueOf(product.getNowPrice()) * product.getBuyCount();
					score+= product.getScore()==null?0:product.getScore();

					orderdetailList.add(orderdetail);
				}
				if(orderdetailList.size()==1){
					order.setRemark(orderdetailList.get(0).getProductName());
				}else{
					order.setRemark("合并|"+orderdetailList.size()+"笔订单");
				}
				
				order.setScore(score);
				order.setExpressCode(curExpress.getCode());//配送方式编码
				order.setExpressName(curExpress.getName());//配送方式名称
				order.setOrderNumber(getOrderNumber());
				order.setFee(order.getPtotal()>=curExpress.getExempt()?0f:curExpress.getFee());//订单配送费,包括满额免邮
				order.setAmount(order.getPtotal()+order.getFee());//订单总金额 = 内存订单总金额 + 总配送费
//				order.setAmountExchangeScore(Integer.valueOf(cartInfo.getTotalExchangeScore()));//订单总兑换积分。订单支付成功以后扣除
				
				/**
				 * 对金额进行格式化，防止出现double型数字计算造成的益出。
				 */
				logger.error("order.getAmount()="+order.getAmount());
				order.setAmount(Double.valueOf(df.format(order.getAmount())));//订单总金额
				order.setPtotal(Double.valueOf(df.format(order.getPtotal())));//订单商品总金额
				order.setFee(Double.valueOf(df.format(order.getFee())));//订单总配送费
				IOrderService orderServ=(IOrderService) getService(OrderServiceImpl.class);
				order.setCreatedate(new Date());
				orderServ.saveEntity(order);
				allOrderList.add(order);
				//处理库存变化
//				for(OrderdetailEntity o:orderdetailList){
//					Long productId=o.getProductID();
//					Integer buyCount=o.getNumber();
//					Long specId=o.get
//					ProductEntity p=prodServ.getEntityById(productId);
//					if(p!=null){
//						
//					}
//				}
				/**
				 * 配送地址信息
				 */
				OrderShipEntity ordership = new OrderShipEntity();
				ordership.setOrderid(order.getId());
				ordership.setShipname(address.getName());
				ordership.setShipaddress(address.getProvince()+address.getCity()+address.getAddress());
				ordership.setProvinceCode(address.getProvince());
				ordership.setProvince(address.getProvince());
				ordership.setCityCode(address.getCity());
				ordership.setCity(address.getCity());
				ordership.setAreaCode(address.getArea());
				ordership.setArea(address.getArea());
				ordership.setPhone(address.getPhone());
				ordership.setTel(address.getMobile());
				ordership.setZip(address.getZip());
				ordership.setSex("1");
				logger.error(ordership.toString());
				
				//创建订单并插入到数据库
				IOrderService orderService=(IOrderService) getService(OrderServiceImpl.class);
				try {
					orderService.createOrder(order, orderdetailList,ordership);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
//				createPayInfo(order,ordership);
				
				//清空购物车内已经购买的商品
				for(Long id:tenantProdMap.keySet()){
					List<ExtCartEntity> lst=tenantProdMap.get(id);
					for(ExtCartEntity c:lst)
						cartServ.deleteByPK(c.getId());
				}
/////////////////////////////////////				
			}
			String orderNumber="";
			if(allOrderList.size()==1){
				orderNumber=allOrderList.get(0).getOrderNumber();
				super.printMsg(resp, "1", orderNumber, "下单成功！");
				return;
			}else if(allOrderList.size()>1){
				orderNumber="m_"+getOrderNumber();
				IOrderTmpService tmpServ=(IOrderTmpService) getService(OrderTmpServiceImpl.class);
				for(OrderEntity o:allOrderList){
					OrderTmpEntity tmp=new OrderTmpEntity();
					tmp.setTmpOrderNumber(orderNumber);
					tmp.setOrderId(o.getId());
					tmp.setOrderNumber(o.getOrderNumber());
					tmpServ.saveEntity(tmp);
				}
				super.printMsg(resp, "1", orderNumber, "下单成功！");
				return;
			}
		}else{
			super.printMsg(resp, "1", "-5", "购物车中没有可下单的商品！");
			return;
		}
	}
	@RequestMapping("submitSingleProductOrder.do")
	public void submitSingleProductOrder(HttpServletRequest req,HttpServletResponse resp,Long productId,Long specId,Integer buyCount,Long addressId,Long expressId,String otherRequirement) throws IOException, IbpdException{
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		} 
		
		IAccountService accServ=(IAccountService) getService(AccountServiceImpl.class);
		AccountEntity account=accServ.getEntityById(super.getCurrentLoginedUserId(req));
		if(account==null){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		
		DecimalFormat df = new DecimalFormat("0.00");
		if(addressId==null || productId==null){
			super.printMsg(resp, "-2", "-2", "非法请求！");
			return;
		}
		if(productId<=0 || addressId<=0){
			super.printMsg(resp, "-2", "-2", "非法请求！");
			return;
		}
		specId=specId==null?-1L:specId;
		buyCount=buyCount==null?1:buyCount;
		buyCount=buyCount<=0?1:buyCount;
		expressId=expressId==null?-1L:expressId;
		if(expressId<=0 || expressId<=0){
			super.printMsg(resp, "-3", "-3", "配送方式错误！");
			return;
		}
		//基于这个新的订单提交接口（兼容购物车和直接 下单），下单逻辑也得重新考虑
		IProductService prodServ=(IProductService) getService(ProductServiceImpl.class);
		ISpecService specServ=(ISpecService) getService(SpecServiceImpl.class);
		IAddressService addServ=(IAddressService) getService(AddressServiceImpl.class);
		IExpressService expServ=(IExpressService) getService(ExpressServiceImpl.class);
		IOrderdetailService detaServ=(IOrderdetailService) getService(OrderdetailServiceImpl.class);
		ProductEntity pe=null;
		SpecEntity spec=null;
		String msg="";
		pe=prodServ.getEntityById(productId);
		//判断商品状态是否正常
		if(pe==null){
			msg+="商品不存在;";
		}else if(!pe.getStatus().equals(ProductEntity.Status_Pass)){
			msg+="商品["+pe.getName()+"]已下架;";
		}else if(pe.getStock()==0){
			msg+="商品["+pe.getName()+"]已经卖完啦;";
		}
		if(!StringUtils.isBlank(msg)){
			super.printMsg(resp, "-4", "-1",msg);
			return;	
		}
		//根据商品以及规格判断是否有库存，如果有规格信息，则走规格的库存，否则走商品的库存
		Boolean stockIsSat=false;
		if(specId==-1L){
			//走商品的库存
			if(pe==null){
				stockIsSat=false;
			}
			if(pe.getStock()>=buyCount){
				stockIsSat=true;
			}
		}else{
			//走规格的库存
			spec=specServ.getEntityById(specId);
			if(spec==null){
				stockIsSat=false;
			}
			if(Integer.valueOf(spec.getSpecStock())>=buyCount){
				stockIsSat=true;
			}
		}
		if(!stockIsSat){
			super.printMsg(resp, "-5", "-1","库存不足!");
			return;	
		}
		//获取配送方式
		ExpressEntity express = expServ.getEntityById(expressId);
		if(express==null){
			super.printMsg(resp, "-7", "-7", "没有编码为"+expressId+"的配送方式！本次请求视为非法！");
			return;
		}
		//获取配送地址
		AddressEntity address = addServ.getEntityById(addressId);
		if(address==null){
			super.printMsg(resp,"-1","-1","根据ID="+addressId+"查询不到配送地址信息！");
			return;
		}
		String proinceName = address.getProvince();//省份名称
		String cityName =address.getCity();//城市名称
		String areaName = address.getArea();
		
		//创建订单对象
		OrderEntity order = new OrderEntity();
		order.setAccount(account.getAccount());
		order.setQuantity(1);//商品款式数量 不是商品 数量
		order.setRebate(1d);
		order.setOrderNumber(getOrderNumber());
		order.setTenantId(pe.getTenantId());
		order.setStatus(OrderEntity.order_status_init);
		order.setPaystatus(OrderEntity.order_paystatus_n);
		order.setOtherRequirement(otherRequirement);//附加要求
		
		//商品总金额
//		double ptotal = 0d;
		int score = 0;//订单积分 等于订单项中每个商品赠送的积分总和
		//创建订单明细集合
			ProductEntity product = pe;
			
			OrderdetailEntity orderdetail = new OrderdetailEntity();
			orderdetail.setProductID(product.getId());
			orderdetail.setGiftID("-1");//商品赠品ID
			orderdetail.setPrice(Double.valueOf((spec!=null)?spec.getSpecPrice().toString():product.getPrice().toString()));//商品现价
			orderdetail.setNumber(buyCount);//购买数
//			orderdetail.setFee(express.getFee());//配送费
			orderdetail.setFee(0.0);//配送费
			orderdetail.setProductName(product.getName());
			orderdetail.setTenantId(product==null?-1L:product.getTenantId());//如果没有对应的供应商，则 把该商品的订单定为总部商品
			orderdetail.setProductImage(product.getMaxPicture());
			orderdetail.setTotal(Double.valueOf(orderdetail.getPrice()) * orderdetail.getNumber());//订单项小计
			orderdetail.setScore(product.getScore());//活的赠送的积分
			if(spec!=null){
				//按照规格计算
				orderdetail.setSpecInfo("尺寸:"+spec.getSpecSize()+",颜色:"+spec.getSpecColor());
			}
			score+= product.getScore()==null?0:product.getScore();

			order.setRemark(orderdetail.getProductName());
		order.setScore(score);
		order.setExpressCode(express.getCode());//配送方式编码
		order.setExpressName(express.getName());//配送方式名称
//		order.setAmountExchangeScore(Integer.valueOf(cartInfo.getTotalExchangeScore()));//订单总兑换积分。订单支付成功以后扣除
		
		/**
		 * 对金额进行格式化，防止出现double型数字计算造成的益出。
		 */
		logger.error("order.getAmount()="+order.getAmount());
		order.setPtotal(Double.valueOf(orderdetail.getPrice()*orderdetail.getNumber()));//订单商品总金额
		order.setFee(order.getPtotal()>=express.getExempt()?0f:express.getFee());//订单配送费,包括满额免邮
		order.setAmount(order.getPtotal()+order.getFee());//订单总金额 = 内存订单总金额 + 总配送费
		IOrderService orderServ=(IOrderService) getService(OrderServiceImpl.class);
		order.setCreatedate(new Date());
		orderServ.saveEntity(order);
		orderdetail.setOrderID(order.getId());
		//detaServ.saveEntity(orderdetail);这里不用保存了，下面会保存的
		//处理库存变化
//		progressStocksChange(cartInfo);
		if(spec!=null){
			spec.setSpecStock((Integer.valueOf((Integer.valueOf(spec.getSpecStock())-buyCount)).toString()));
			specServ.saveEntity(spec);
		}else{
			pe.setStock(pe.getStock()-buyCount);
		}
		pe.setSellcount(pe.getSellcount()+buyCount);
		prodServ.saveEntity(pe);
		/**
		 * 配送地址信息
		 */
		OrderShipEntity ordership = new OrderShipEntity();
		ordership.setOrderid(order.getId());
		ordership.setShipname(address.getName());
		ordership.setShipaddress(proinceName+cityName+address.getAddress());
		ordership.setProvinceCode(address.getProvince());
		ordership.setProvince(proinceName);
		ordership.setCityCode(address.getCity());
		ordership.setCity(cityName);
		ordership.setAreaCode(address.getArea());
		ordership.setArea(areaName);
		ordership.setPhone(address.getPhone());
		ordership.setTel(address.getMobile());
		ordership.setZip(address.getZip());
		ordership.setSex("1");
		logger.error(ordership.toString());
		
		//创建订单并插入到数据库
		IOrderService orderService=(IOrderService) getService(OrderServiceImpl.class);
		try {
			List<OrderdetailEntity> orderdetailList=new ArrayList<OrderdetailEntity>();
			orderdetailList.add(orderdetail);
			orderService.createOrder(order, orderdetailList,ordership);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		super.printMsg(resp,"1",order.getOrderNumber(),"购物车提交成功;orderId:"+order.getOrderNumber());
	}
	private String getOrderNumber(){
		String s=DateUtils.format(new Date(), "YYYYMMdd");
		int n = (int) (Math.random() * 100000);
		return (s+n);
	}
	public static void main(String[] args){
	}
	/**
	 * 暂时废除
	 * @param req
	 * @param resp
	 * @param addressId
	 * @param expressCode
	 * @param otherRequirement
	 * @throws IOException
	 * @throws IbpdException
	 */
	@RequestMapping("submitOrder.do")
	public void submitOrder(HttpServletRequest req,HttpServletResponse resp,String addressId,String expressCode,String otherRequirement) throws IOException, IbpdException{
//		AccountEntity account = InterfaceUtil.getLoginedAccountInfo(req.getSession());
//		if (account == null || StringUtils.isBlank(account.getAccount())) {
//			super.printMsg(resp, "0", "0", "请先登录");
//			return;
//		}
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		
		IAccountService accServ=(IAccountService) getService(AccountServiceImpl.class);
		AccountEntity account=accServ.getEntityById(super.getCurrentLoginedUserId(req));
		if(account==null){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		
		DecimalFormat df = new DecimalFormat("0.00");
		if(StringUtils.isBlank(addressId) || StringUtils.isBlank(expressCode)){
			super.printMsg(resp, "-2", "-2", "非法请求！");
			return;
		}

		//获取用户购买的商品列表
		ICartService cartServ=(ICartService) getService(CartServiceImpl.class);
		List<CartEntity> cartProductList=cartServ.getCartProductListByUserId(super.getCurrentLoginedUserId(req));
		if (cartProductList == null || cartProductList.size() == 0) {
			super.printMsg(resp, "-3", "-3", "购物车中没有可支付的商品!");
			return;
		}
		ExtCartInfo cartInfo = fillCartInfo(cartProductList,super.getCurrentLoginedUserId(req));
		
		//检测商品是否都有库存,如果没有库存需要提醒用户
		String msg="";
		synchronized (product_stock_lock) {
			boolean no = false;
			ISpecService specServ=(ISpecService) getService(SpecServiceImpl.class);
			IProductService productServ=(IProductService) getService(ProductServiceImpl.class);
			for (int i = 0; i < cartInfo.getProductList().size(); i++) {
				CartEntity product = cartInfo.getProductList().get(i);
				if(product.getSpecId()==null || product.getSpecId()<=0){
					ProductEntity pe=productServ.getEntityById(product.getProductId());
					if(pe==null){
						msg+="商品["+product.getProductName()+"]不存在;";
					}else if(pe.getStatus()!=ProductEntity.Status_Pass){
						msg+="商品["+product.getProductName()+"]已下架;";
					}else if(pe.getStock()==0){
						msg+="商品["+product.getProductName()+"]已经卖完啦;";
					}else if(pe.getStock()<product.getBuyCount()){
						msg+="商品["+product.getProductName()+"]库存不足;";
					}
				}else{
					SpecEntity se=specServ.getEntityById(product.getSpecId());
					if(se==null){
						msg+="规格为[+"+product.getSpecColor()+":+"+product.getSpecSize()+"]的"+product.getProductName()+"已经下架啦;";
					}else if((Integer.valueOf((se.getSpecStock()==null)?"0":se.getSpecStock()))==0){
						msg+="商品["+product.getProductName()+"]已经卖完啦;";
					}else if((Integer.valueOf((se.getSpecStock()==null)?"0":se.getSpecStock()))<product.getBuyCount()){
						msg+="商品["+product.getProductName()+"]库存不足;";
					}
					
				}
			}
			//库存不足，则刷最后支付页面，提示用户某些商品的库存不足，请重新选购
		if(!StringUtil.isBlank(msg)){
				super.printMsg(resp, "-4", "-4", msg);
				return;				
			}
			
		}
		
		//获取配送方式
		IExpressService expServ=(IExpressService)ServiceProxyFactory.getServiceProxy(ExpressServiceImpl.class);
		ExpressEntity express = expServ.getEntityByCode(expressCode);
		if(express==null){
			super.printMsg(resp, "-7", "-7", "没有编码为"+expressCode+"的配送方式！本次请求视为非法！");
			return;
		}
		//获取配送地址
		IAddressService addressService=(IAddressService) getService(AddressServiceImpl.class);
		AddressEntity address = addressService.getEntityById(Long.valueOf(addressId));
		if(address==null){
			super.printMsg(resp,"-1","-1","根据ID="+addressId+"查询不到配送地址信息！");
			return;
		}
		logger.error(address.toString());
		IAreaService areaServ=(IAreaService) getService(AreaServiceImpl.class);
//		AreaEntity area = areaServ.getAreaByName((address.getProvince()==null)?"":address.getProvince());//获取省份对象
//		if(area==null){
//			super.printMsg(resp, "-6", "-6", "没有找到配送地域信息，本次请求视为非法！");
//			return;
//		}
		String proinceName = address.getProvince();//省份名称
		String cityName =address.getCity();//城市名称
		String areaName = address.getArea();
//		AreaEntity city=areaServ.getAreaByName((address.getCity()==null)?"":address.getCity());
//		if(city==null){
//			super.printMsg(resp, "-6", "-6", "没有找到配送地域信息，本次请求视为非法！");
//			return;			
//		}
//		cityName=city.getName();
//		List<AreaEntity> citys = areaServ.getAreaListByParentCode(area.getCode());
//		if(citys!=null && citys.size()>0){
//			for(int i=0;i<citys.size();i++){
//				AreaEntity cityItem = citys.get(i);
//				if(cityItem.getCode().equals(address.getCity())){
//					cityName = cityItem.getName();
//					
//					//获取所在区域名称
//					if(StringUtils.isNotBlank(address.getArea())){
//						List<AreaEntity> areaList = areaServ.getAreaListByParentCode(cityItem.getCode());
//						if(areaList!=null && areaList.size()>0){
//							for(int m=0;m<areaList.size();m++){
//								areaName = areaList.get(m).getName();
//							}
//						}
//					}
//				}
//			}
//		}
		
		//创建订单对象
		OrderEntity order = new OrderEntity();
		order.setAccount(account.getAccount());
		order.setQuantity(cartInfo.getProductList().size());
		order.setRebate(1d);
		order.setStatus(OrderEntity.order_status_init);
		order.setPaystatus(OrderEntity.order_paystatus_n);
		order.setOtherRequirement(otherRequirement);//附加要求
		
		//商品总金额
//		double ptotal = 0d;
		int score = 0;//订单积分 等于订单项中每个商品赠送的积分总和
		//创建订单明细集合
		List<OrderdetailEntity> orderdetailList = new LinkedList<OrderdetailEntity>();
		IProductService prodServ=(IProductService) getService(ProductServiceImpl.class);
		for (int i = 0; i < cartInfo.getProductList().size(); i++) {
			CartEntity product = cartInfo.getProductList().get(i);
			
			OrderdetailEntity orderdetail = new OrderdetailEntity();
			orderdetail.setProductID(product.getId());
			orderdetail.setGiftID("-1");//商品赠品ID
			orderdetail.setPrice(Double.valueOf(product.getSpecPrice().toString()));//商品现价
			orderdetail.setNumber(product.getBuyCount());//购买数
			orderdetail.setFee(0.0);//配送费
			orderdetail.setProductName(product.getProductName());
			ProductEntity p=prodServ.getEntityById(product.getProductId());
			orderdetail.setTenantId(p==null?-1L:p.getTenantId());//如果没有对应的供应商，则 把该商品的订单定为总部商品
			orderdetail.setProductImage(p.getMaxPicture());
			orderdetail.setTotal(Double.valueOf(orderdetail.getPrice()) * orderdetail.getNumber());//订单项小计
			orderdetail.setScore(product.getScore());//活的赠送的积分
			if(product.getSpecId()!=null && product.getSpecId()>=0L){
				//按照规格计算
				orderdetail.setSpecInfo("尺寸:"+product.getSpecSize()+",颜色:"+product.getSpecColor());
//				ptotal+= Double.valueOf(product.getBuySpecInfo().getSpecPrice()) * product.getBuyCount();
//				score+= product.getScore();
			}
//			ptotal+= Double.valueOf(product.getNowPrice()) * product.getBuyCount();
			score+= product.getScore()==null?0:product.getScore();

			orderdetailList.add(orderdetail);
		}
		if(orderdetailList.size()==1){
			order.setRemark(orderdetailList.get(0).getProductName());
		}else{
			order.setRemark("合并|"+orderdetailList.size()+"笔订单");
		}
		
		order.setScore(score);
		order.setExpressCode(express.getCode());//配送方式编码
		order.setExpressName(express.getName());//配送方式名称
		order.setFee(express.getFee());//订单配送费
		order.setPtotal(Double.valueOf(cartInfo.getAmount()));//订单商品总金额
		order.setAmount(Double.valueOf(Double.valueOf(cartInfo.getAmount())+Double.valueOf(order.getFee())));//订单总金额 = 内存订单总金额 + 总配送费
//		order.setAmountExchangeScore(Integer.valueOf(cartInfo.getTotalExchangeScore()));//订单总兑换积分。订单支付成功以后扣除
		
		/**
		 * 对金额进行格式化，防止出现double型数字计算造成的益出。
		 */
		logger.error("order.getAmount()="+order.getAmount());
		order.setAmount(Double.valueOf(df.format(order.getAmount())));//订单总金额
		order.setPtotal(Double.valueOf(df.format(order.getPtotal())));//订单商品总金额
		order.setFee(Double.valueOf(df.format(order.getFee())));//订单总配送费
		IOrderService orderServ=(IOrderService) getService(OrderServiceImpl.class);
		order.setCreatedate(new Date());
		orderServ.saveEntity(order);
		//处理库存变化
		progressStocksChange(cartInfo);
		/**
		 * 配送地址信息
		 */
		OrderShipEntity ordership = new OrderShipEntity();
		ordership.setOrderid(order.getId());
		ordership.setShipname(address.getName());
		ordership.setShipaddress(proinceName+cityName+address.getAddress());
		ordership.setProvinceCode(address.getProvince());
		ordership.setProvince(proinceName);
		ordership.setCityCode(address.getCity());
		ordership.setCity(cityName);
		ordership.setAreaCode(address.getArea());
		ordership.setArea(areaName);
		ordership.setPhone(address.getPhone());
		ordership.setTel(address.getMobile());
		ordership.setZip(address.getZip());
		ordership.setSex("1");
		logger.error(ordership.toString());
		
		//创建订单并插入到数据库
		IOrderService orderService=(IOrderService) getService(OrderServiceImpl.class);
		try {
			orderService.createOrder(order, orderdetailList,ordership);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
//		createPayInfo(order,ordership);
		
		//清空购物车
		cartServ.clearCart(super.getCurrentLoginedUserId(req));
		super.printMsg(resp,"0","0","购物车提交成功;orderId:"+order.getId());
	}
	/**
	 * 处理销量跟库存
	 * @param info
	 */
	private void progressStocksChange(ExtCartInfo info){
		IProductService prodServ=(IProductService) getService(ProductServiceImpl.class);
		ISpecService specServ=(ISpecService) getService(SpecServiceImpl.class);
		for( CartEntity prod:info.getProductList()){
			ProductEntity product=prodServ.getEntityById(prod.getProductId());
			if(product==null)
				continue;
			product.setSellcount(product.getSellcount()+prod.getBuyCount());
			if(prod.getSpecId()!=null && prod.getSpecId()>0L){
				SpecEntity spec=specServ.getEntityById(prod.getSpecId());
				if(spec!=null){
					Integer curStock=Integer.valueOf(spec.getSpecStock());
					curStock=curStock-prod.getBuyCount();
					curStock=curStock>=0?curStock:0;
					spec.setSpecStock(curStock.toString());
					specServ.saveEntity(spec);
				}else{
					logger.error("处理库存过程中,发现ID为"+prod.getSpecId()+"的规格没有信息");
				}
			}else{
				product.setStock(product.getStock()-prod.getBuyCount());
				product.setStock(product.getStock()<0?0:product.getStock());
			}
			prodServ.saveEntity(product);
		}
	}
	@RequestMapping("delUserOrder.do")
	public void delUserOrder(HttpServletResponse resp,HttpServletRequest req,Long orderId) throws IOException{
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		if(orderId==null || orderId<=0L){
			super.printMsg(resp, "-2", "-2","参数错误!");
		}
		IOrderService orderServ=(IOrderService) getService(OrderServiceImpl.class);
		IOrderdetailService detaServ=(IOrderdetailService) getService(OrderdetailServiceImpl.class);
		IOrderShipService shipServ=(IOrderShipService) getService(OrderShipServiceImpl.class);
		IOrderpayService payServ=(IOrderpayService) getService(OrderpayServiceImpl.class);
		if(orderServ.getEntityById(orderId)==null){
			super.printMsg(resp, "-1", "-1","没有该订单");
			return;
		}
		OrderEntity oe=orderServ.getEntityById(orderId);
		if(oe==null){
			super.printMsg(resp, "-4", "-4","没有该订单");
			return; 
		}
		orderServ.deleteByPK(orderId);
		detaServ.deleteByOrderId(orderId);
		shipServ.deleteByOrderId(orderId);
		payServ.deleteByOrderId(orderId);
		super.printMsg(resp, "99", "99","执行成功");
	}
	@RequestMapping("submitPayStatus.do")
	public void submitPayStatus(HttpServletResponse resp,HttpServletRequest req,Long orderId,String payType,String status) throws IOException{
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		payType=(payType==null)?"":payType;
		status=(status==null)?"":status;
		orderId=(orderId==null)?-1L:orderId;
		if(StringUtils.isBlank(payType) || StringUtils.isBlank(status) || orderId==-1L){
			super.printMsg(resp, "-2", "-1", "参数错误");
			return;
		}
		IOrderService os=(IOrderService) getService(OrderServiceImpl.class);
		OrderEntity o=os.getEntityById(orderId);
		if(o==null){
			super.printMsg(resp, "-2", "-1", "没有该订单");
			return;
		}
//		if(!o.getStatus().equals(OrderEntity.order_status_pass)){
//			super.printMsg(resp, "-3", "-1", "订单尚未审核");
//			return;			
//		}
		status=(status.toLowerCase().equals("y"))?"y":"n";
		payType=(payType.toLowerCase().equals("zfb"))?orderpay_paymethod_alipayescow:payType;
		o.setPaystatus(status);
		o.setStatus(status.equals("y")?OrderEntity.order_status_pass:o.getStatus());
		os.saveEntity(o);
		IOrderpayService opServ=(IOrderpayService) getService(OrderpayServiceImpl.class);
		OrderpayEntity op=opServ.getOrderpayByOrderId(o.getId());
		op=(op==null)?new OrderpayEntity():op;
		op.setConfirmdate(new Date());
		op.setCreatetime(new Date());
		op.setOrderid(orderId.toString());
		op.setPayamount(o.getAmount());
		op.setPaymethod(payType);
		op.setPaystatus(status);
		op.setRemark("");
//		op.setCreatetime(new Date());
//		op.setConfirmdate(new Date());
//		op.setConfirmuser(InterfaceUtil.get)
		opServ.saveEntity(op);
		super.printMsg(resp, "0", "0", "状态保存成功");
	}
	@RequestMapping("signOrder.do")
	public void submitPayStatus(HttpServletResponse resp,HttpServletRequest req,Long orderId) throws IOException{
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		orderId=(orderId==null)?-1L:orderId;
		IOrderService os=(IOrderService) getService(OrderServiceImpl.class);
		OrderEntity o=os.getEntityById(orderId);
		if(o==null){
			super.printMsg(resp, "-2", "-1", "没有该订单");
			return;
		}
		if(o.getStatus().equals(OrderEntity.order_status_send)){
			o.setStatus(OrderEntity.order_status_sign);
			os.saveEntity(o);
			super.printMsg(resp, "0", "0", "状态保存成功");			
		}else{
			super.printMsg(resp, "-3", "-1", "操作非法");	
		}
	}
	@RequestMapping("getOrderList.do")
	public void getOrderList(HttpServletRequest req,HttpServletResponse resp,Integer pageSize,Integer pageIndex) throws IOException{
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		IAccountService accServ=(IAccountService) getService(AccountServiceImpl.class);
		AccountEntity acc=accServ.getEntityById(super.getCurrentLoginedUserId(req));
		
//		AccountEntity acc = InterfaceUtil.getLoginedAccountInfo(req.getSession());
		if(acc==null || StringUtils.isBlank(acc.getAccount())){
			super.printMsg(resp, "-2", "-1", "尚未登录或登录已经失效");
			return;
		}
		pageSize=(pageSize==null)?10:pageSize;
		pageSize=(pageSize<=0)?10:pageSize;
		pageIndex=(pageIndex==null)?0:pageIndex;
		pageIndex=(pageIndex<0)?0:pageIndex;
		IOrderService orderServ=(IOrderService) getService(OrderServiceImpl.class);
		List<OrderEntity> orderList=orderServ.getListByAccount(acc.getAccount(),pageSize,pageIndex);
		if(orderList==null || orderList.size()==0){
			super.printMsg(resp, "-3", "-1", "没有该用户订单");
			return;
		}
		List<ExtOrderEntity> extOrderList=new ArrayList<ExtOrderEntity>();
		for(OrderEntity o:orderList){
			ExtOrderEntity ext=new ExtOrderEntity(o);
//			IOrderService orderServ=(IOrderService) getService(OrderServiceImpl.class);
			OrderEntity order=orderServ.getEntityById(o.getId());
			if(order==null){
				//super.printMsg(resp, "-2", "-1", "没有该订单");
				break;
			}
			ExtOrderInfoEntity orderInfo=new ExtOrderInfoEntity(order);
			IOrderdetailService detailServ=(IOrderdetailService) getService(OrderdetailServiceImpl.class);
			List<OrderdetailEntity> detailList=detailServ.getListByOrderId(order.getId());
			orderInfo.setDetailList(detailList);
			IOrderpayService payServ=(IOrderpayService) getService(OrderpayServiceImpl.class);
			OrderpayEntity pay=payServ.getOrderpayByOrderId(order.getId());
			orderInfo.setOrderpay(pay);
			IOrderShipService shipServ=(IOrderShipService) getService(OrderShipServiceImpl.class);
			OrderShipEntity ship=shipServ.getOrderShipByOrderId(order.getId());
			orderInfo.setOrderShip(ship);
			ext.setInfo(orderInfo);
			extOrderList.add(ext);
		}
		super.sendJsonByList(resp, extOrderList, Long.valueOf(orderList.size()));
	}
	@RequestMapping("getOrderInfo.do")
	public void getOrderInfo(HttpServletRequest req,HttpServletResponse resp,Long orderId) throws IOException{
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		IAccountService accServ=(IAccountService) getService(AccountServiceImpl.class);
		AccountEntity acc=accServ.getEntityById(super.getCurrentLoginedUserId(req));
		
//		AccountEntity acc = InterfaceUtil.getLoginedAccountInfo(req.getSession());
		if(acc==null || StringUtils.isBlank(acc.getAccount())){
			super.printMsg(resp, "-2", "-1", "尚未登录或登录已经失效");
			return;
		}
		if(orderId==null || orderId<=0L){
			super.printMsg(resp, "-3", "-1", "参数错误");
			return;
		}
		IOrderService orderServ=(IOrderService) getService(OrderServiceImpl.class);
//		orderServ.getDao().clearCache();
		OrderEntity order=orderServ.getEntityById(orderId);
		if(order==null){
			super.printMsg(resp, "-2", "-1", "没有该订单");
			return;
		}
		ExtOrderInfoEntity orderInfo=new ExtOrderInfoEntity(order);
		IOrderdetailService detailServ=(IOrderdetailService) getService(OrderdetailServiceImpl.class);
		List<OrderdetailEntity> detailList=detailServ.getListByOrderId(order.getId());
		orderInfo.setDetailList(detailList);
		IOrderpayService payServ=(IOrderpayService) getService(OrderpayServiceImpl.class);
		OrderpayEntity pay=payServ.getOrderpayByOrderId(order.getId());
		orderInfo.setOrderpay(pay);
		IOrderShipService shipServ=(IOrderShipService) getService(OrderShipServiceImpl.class);
		OrderShipEntity ship=shipServ.getOrderShipByOrderId(order.getId());
		orderInfo.setOrderShip(ship);
		List<ExtOrderInfoEntity> infoList=new ArrayList<ExtOrderInfoEntity>();
		infoList.add(orderInfo);
		super.sendJsonByList(resp, infoList, Long.valueOf(infoList.size()));
	}
	@RequestMapping("refundOrder.do")
	public void refundOrder(Long orderId,String remark,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		IAccountService accServ=(IAccountService) getService(AccountServiceImpl.class);
		AccountEntity acc=accServ.getEntityById(super.getCurrentLoginedUserId(req));
		
//		AccountEntity acc = InterfaceUtil.getLoginedAccountInfo(req.getSession());
		if(acc==null || StringUtils.isBlank(acc.getAccount())){
			super.printMsg(resp, "-2", "-1", "尚未登录或登录已经失效");
			return;
		}
		if(orderId==null || orderId<=0){
			super.printMsg(resp, "-3", "-2","参数错误");
			return;			
		}
		IOrderService ordServ=(IOrderService) getService(OrderServiceImpl.class);
		OrderEntity ord=ordServ.getEntityById(orderId);
		if(ord==null){
			super.printMsg(resp, "-4", "-3","没有该订单");
			return;			
		}
		if(!ord.getAccount().equals(acc.getAccount())){
			super.printMsg(resp, "-5", "-4","无效的申请");
			return;			
		}
		if(ord.getStatus().equals(OrderEntity.order_status_send)){
			ord.setRefundRemark(remark);
			ord.setRefundStatus(OrderEntity.order_refund_status_init);
			ordServ.saveEntity(ord);
			super.printMsg(resp, "0", "0","执行成功");
		}else{
			super.printMsg(resp, "-4", "-4","无效的申请");
			return;	
		}
	}
	@RequestMapping("getMallHomeProductList.do")
	public void getMallHomeProductList(HttpServletResponse resp,HttpServletRequest req,String type,Integer rowCount) throws IOException{
		type=type==null?"all":type;
		type=type.equals("")?"all":type;
		rowCount=rowCount==null?5:rowCount;
		rowCount=rowCount<=0?5:rowCount;
		Integer tp=-1;
		if(type.toLowerCase().trim().equals("all")){
			tp=-1;
		}else if(type.toLowerCase().trim().equals("pop")){
			tp=MallHomePageEntity.TYPE_幻灯;
		}else if(type.toLowerCase().trim().equals("jrtj")){
			tp=MallHomePageEntity.TYPE_今日推荐;
		}else if(type.toLowerCase().trim().equals("rmsc")){
			tp=MallHomePageEntity.TYPE_热门市场;
		}else if(type.toLowerCase().trim().equals("hyzm")){
			tp=MallHomePageEntity.TYPE_会员专卖;
		}
		IMallHomePageService homeServ=(IMallHomePageService) getService(MallHomePageServiceImpl.class);
		List<MallHomePageEntity>  lst=homeServ.getListByType(tp,rowCount);
		if(lst==null)
			lst=new ArrayList<MallHomePageEntity>();
		List<ExtMallHomePageEntity> extList=new ArrayList<ExtMallHomePageEntity>();
		IProductService prodServ=(IProductService) getService(ProductServiceImpl.class);
		for(MallHomePageEntity mall:lst){
			ExtMallHomePageEntity ext=new ExtMallHomePageEntity(mall);
			ProductEntity prod=prodServ.getEntityById(mall.getProductId());
			if(prod==null){
				continue;
			}
			ext.setProductName(prod.getName());
			ext.setPrice(prod.getNowPrice());
			ext.setImage(prod.getMaxPicture());
			extList.add(ext);
		}
		super.sendJsonByList(resp, extList, Long.valueOf(extList.size()));
	}
	@RequestMapping("chanageCartProductCount.do")
	public void chanageCartProductCount(HttpServletResponse resp,HttpServletRequest req,Long productId,Integer count) throws IOException{
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		if(productId==null || productId<=0 || count==null || count<=0){
			super.printMsg(resp, "-3", "-1","参数错误!");
			return;			
		}
		ICartService cartServ=(ICartService) getService(CartServiceImpl.class);
		List<CartEntity> cartList=cartServ.getCartProductListByUserId(super.getCurrentLoginedUserId(req));
		if(cartList==null){
			super.printMsg(resp, "-2", "-1","购物车内无商品");
			return;			
		}
		CartEntity ce=null;
		for(CartEntity c:cartList){
			if(c.getProductId().equals(productId)){
				ce=c;
				break;
			}
		}
		if(ce==null){
			super.printMsg(resp, "-2", "-1","购物车内无此商品");
			return;			
		}else{
			ce.setBuyCount(count);
			cartServ.saveEntity(ce);
			super.printMsg(resp, "1", "1","修改成功");
			return;			
		}
	}
	@RequestMapping("removeCartProduct.do")
	public void removeCartProductCount(HttpServletResponse resp,HttpServletRequest req,Long productId) throws IOException{
		if(super.getCurrentLoginedUserId(req)==-1L){
			super.printMsg(resp, "-1", "-1","请先登录!");
			return;			
		}
		if(productId==null || productId<=0){
			super.printMsg(resp, "-3", "-1","参数错误!");
			return;			
		}
		ICartService cartServ=(ICartService) getService(CartServiceImpl.class);
		List<CartEntity> cartList=cartServ.getCartProductListByUserId(super.getCurrentLoginedUserId(req));
		if(cartList==null){
			super.printMsg(resp, "-2", "-1","购物车内无商品");
			return;			
		}
		CartEntity ce=null;
		for(CartEntity c:cartList){
			if(c.getProductId().equals(productId)){
				ce=c;
				break;
			}
		}
		if(ce==null){
			super.printMsg(resp, "-2", "-1","购物车内无此商品");
			return;			
		}else{
			cartServ.deleteByPK(ce.getId());
			super.printMsg(resp, "1", "1","执行成功");
			return;			
		}
	}
}
